using System.IO;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Net;
using Android.OS;
using Android.Text;
using Android.Text.Util;
using Android.Views;
using Android.Widget;
using Java.IO;
using Java.Lang;
using Xamarin.ActionbarSherlockBinding.App;

namespace Cinemacenter.Droid
{
	public class AboutFragment : SherlockDialogFragment
	{
		public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
		{
			base.OnCreateView (inflater, container, savedInstanceState);

			var view = inflater.Inflate (Resource.Layout.DialogAbout, container, false);
			Dialog.SetTitle (Resource.String.menu_about);
			var tv = view.FindViewById<TextView> (Resource.Id.legal_text);
			tv.TextFormatted = Html.FromHtml (ReadRawTextFile (Resource.Raw.legal));
			Linkify.AddLinks (tv, MatchOptions.All);
			tv = view.FindViewById<TextView> (Resource.Id.info_text);
			tv.TextFormatted = Html.FromHtml (ReadRawTextFile (Resource.Raw.info));
			tv.SetLinkTextColor (Color.Red);
			Linkify.AddLinks (tv, MatchOptions.All);

			var button2 = view.FindViewById<Button> (Resource.Id.nothanks_button);
			button2.SetTextSize (Android.Util.ComplexUnitType.Sp, 18);
			button2.Click += delegate {
				ISharedPreferences prefs = Application.Context.GetSharedPreferences (
					                           "apprater", 0);
				ISharedPreferencesEditor editor = prefs.Edit ();
				editor.PutBoolean ("dontshowagain", true);
				editor.Commit ();
				Dismiss ();
			};

			var button1 = view.FindViewById<Button> (Resource.Id.rate_button);
			button1.SetTextSize (Android.Util.ComplexUnitType.Sp, 18);
			button1.Click += delegate {

				var uri = Android.Net.Uri.Parse ("market://details?id="	+ Application.Context.PackageName);
				var goToMarket = new Intent (Intent.ActionView, uri);
				goToMarket.SetFlags (ActivityFlags.NewTask);
				try {
					Application.Context.StartActivity (goToMarket);
					var handler = new Handler ();

					var r = new Runnable (() => { 
						button2.SetText (Resource.String.done);
						button1.Visibility = ViewStates.Invisible;
					});

					handler.PostDelayed (r, 2000);

				} catch (ActivityNotFoundException ex) {
					System.Console.WriteLine (ex);
					Toast.MakeText (Application.Context,
						"No se pudo iniciar Google Play Store",
						ToastLength.Short).Show ();
				}
			};

			return view;
		}


		public static string ReadRawTextFile (int id)
		{
			Stream inputStream = Application.Context.Resources.OpenRawResource (id);
			var input = new InputStreamReader (inputStream);
			var buf = new BufferedReader (input);
			string line;
			var text = new StringBuilder ();
			try {
				while ((line = buf.ReadLine ()) != null)
					text.Append (line);
			} catch (Java.IO.IOException ex) {
				System.Console.WriteLine (ex);
				return null;
			}
			return text.ToString ();
		}
	}
}
